package com.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.demo.bean.*;
import com.demo.common.Result;
import com.demo.repositories.PatentRepository;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;


@Controller
public class PatentController {
    @Autowired
    private PatentRepository patentRepository;
    @RequestMapping("/")
    public String toIndex(Model model){
        model.addAttribute("page","patent");
        return "views/patent/patentList";
    }

    @RequestMapping("getList")
    @ResponseBody
    public Result getList(@RequestBody SearchParam searchParam){
        System.out.println(searchParam);
        Pageable pageable= PageRequest.of(searchParam.getPage()-1,searchParam.getLimit());
        Page<Patent> all = patentRepository.findAll(pageable);
        int numberOfElements = all.getNumberOfElements();

        Map<String,Object>resultMap=new HashMap<>();
        resultMap.put("data",all.get().toArray());
        resultMap.put("count",all.getTotalElements());
        resultMap.put("code",0);
        resultMap.put("msg","ok");
        //查询条件组装
        return Result.ok().Data(resultMap);
    }
    @RequestMapping("getPageList")
    @ResponseBody
    public Result getPageList(@RequestBody SearchParam searchParam){
        Pageable pageable= PageRequest.of(searchParam.getPage()-1,searchParam.getLimit());
        Page<Patent> data=null;
        if(StringUtils.isNotEmpty(searchParam.getTitle())&&StringUtils.isEmpty(searchParam.getApplyNum())){
            data = patentRepository.getPageListByTitle(searchParam.getTitle(),pageable);
        }else
        if(StringUtils.isNotEmpty(searchParam.getApplyNum())&&StringUtils.isEmpty(searchParam.getTitle())){
            data = patentRepository.getPageListByapplyNum(searchParam.getApplyNum(),pageable);
        }else
        if(StringUtils.isNotEmpty(searchParam.getTitle())&&StringUtils.isNotEmpty(searchParam.getApplyNum())){
            data = patentRepository.getPageListByTitleAndapplyNum(searchParam.getTitle(),searchParam.getApplyNum(), pageable);
        }else
        if(StringUtils.isEmpty(searchParam.getTitle())&&StringUtils.isEmpty(searchParam.getApplyNum())){
            data = patentRepository.findAll(pageable);
        }
        Map<String,Object>resultMap=new HashMap<>();
        resultMap.put("data",data.get().toArray());
        resultMap.put("count",data.getTotalElements());
        resultMap.put("code",0);
        resultMap.put("msg","ok");
        //查询条件组装
        return Result.ok().Data(resultMap);
    }

    @RequestMapping("getById")
    @ResponseBody
    public Result getById(@RequestParam("id") Long id){

        Optional<Patent> byId = patentRepository.findById(id);
        return Result.ok().Data(byId.get());
    }

    @RequestMapping("delById")
    @ResponseBody
    public Result delById(@RequestParam("id") Long id){
        patentRepository.deleteById(id);
        return Result.ok();
    }

    @RequestMapping("toUpload")
    public String toUploadLayer(){
        return "views/patent/uploadLayer";
    }


    @RequestMapping("toInfo")
    public String toInfo(@RequestParam("id")Long id, Model model){
        model.addAttribute("id",id);
        return "views/patent/patentInfo";
    }


    @RequestMapping("/genPublic")
    @ResponseBody
    public String genPublic(HttpServletResponse response) throws IOException {
        ApplicationHome h = new ApplicationHome(getClass());
        File jarF = h.getSource();
        String name="00公开号";
        Iterable<Patent> all = patentRepository.findAll();
        StringBuilder stringBuilder=new StringBuilder();
        Iterator<Patent> i=all.iterator();
        while (i.hasNext()){
            Patent patent = i.next();
            if(patent.getPublicNum()!=null){
                Map<String, String> map = JSON.parseObject(patent.getPublicNum(), new TypeReference<Map<String, String>>(){});
                stringBuilder.append("pubid:"+map.get("country").toString()+map.get("docNumber").toString());
                stringBuilder.append("\n");
                stringBuilder.append("data:"+map.get("country").toString()+"-"+map.get("docNumber").toString()+"-"+map.get("kind")+"-"+map.get("date"));
                stringBuilder.append("\n");
            }
        }
        String path=jarF.getParentFile().toString()+File.separator+"upload"+File.separator+name+".txt";
        FileUtils.writeStringToFile(new File(path),stringBuilder.toString());
            //设置文件路径
            File file = new File(path);
            //File file = new File(realPath , fileName);
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.setCharacterEncoding("utf-8");
                try {
                    name= URLEncoder.encode(name, "UTF-8").replaceAll("\\+", "%20");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
//                response.setContentType("application/octet-stream");

                // 将文件写入输入流
                FileInputStream fileInputStream = null;
                try {
                    fileInputStream = new FileInputStream(file);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                InputStream fis = new BufferedInputStream(fileInputStream);
                byte[] buffer = new byte[0];
                try {
                    buffer = new byte[fis.available()];
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    fis.read(buffer);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

// 清空response
                response.reset();
                try {
//                    fis = new FileInputStream(file);
//                    bis = new BufferedInputStream(fis);
                    OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
                    response.setContentType("application/octet-stream");
                    response.addHeader("Content-Length", "" + file.length());
                    // 设置文件头：最后一个参数是设置下载文件名
                    response.setHeader("Content-disposition", "attachment;filename="+name+".txt");
                    outputStream.write(buffer);
                    outputStream.flush();
                    return "下载成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally { // 做关闭操作

                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

        return "下载失败";

    }

    @RequestMapping("/genApply")
    @ResponseBody
    public String genApply(HttpServletResponse response) throws IOException {
        ApplicationHome h = new ApplicationHome(getClass());
        File jarF = h.getSource();
        String name="01申请号";
        Iterable<Patent> all = patentRepository.findAll();
        StringBuilder stringBuilder=new StringBuilder();
        Iterator<Patent> i=all.iterator();
        while (i.hasNext()){
            Patent patent = i.next();
            if(patent.getApplyNum()!=null){
                Map<String, String> map = JSON.parseObject(patent.getApplyNum(), new TypeReference<Map<String, String>>(){});
                stringBuilder.append("appid:"+map.get("country").toString()+map.get("docNumber").toString());
                stringBuilder.append("\n");
                stringBuilder.append("data:"+map.get("country").toString()+"-"+map.get("docNumber").toString()+"-"+map.get("kind")+"-"+map.get("date"));
                stringBuilder.append("\n");
            }
        }
        String path=jarF.getParentFile().toString()+File.separator+"upload"+File.separator+name+".txt";
        FileUtils.writeStringToFile(new File(path),stringBuilder.toString());
        //设置文件路径
        File file = new File(path);
        //File file = new File(realPath , fileName);
        if (file.exists()) {
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.setCharacterEncoding("utf-8");
            try {
                name= URLEncoder.encode(name, "UTF-8").replaceAll("\\+", "%20");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
//                response.setContentType("application/octet-stream");

            // 将文件写入输入流
            FileInputStream fileInputStream = null;
            try {
                fileInputStream = new FileInputStream(file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[0];
            try {
                buffer = new byte[fis.available()];
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fis.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

// 清空response
            response.reset();
            try {
//                    fis = new FileInputStream(file);
//                    bis = new BufferedInputStream(fis);
                OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                response.addHeader("Content-Length", "" + file.length());
                // 设置文件头：最后一个参数是设置下载文件名
                response.setHeader("Content-disposition", "attachment;filename="+name+".txt");
                outputStream.write(buffer);
                outputStream.flush();
                return "下载成功";
            } catch (Exception e) {
                e.printStackTrace();
            } finally { // 做关闭操作

                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        return "下载失败";

    }

    @RequestMapping("/genTitle")
    @ResponseBody
    public String genTitle(HttpServletResponse response) throws IOException {
        ApplicationHome h = new ApplicationHome(getClass());
        File jarF = h.getSource();
        String name="02标题";
        Iterable<Patent> all = patentRepository.findAll();
        StringBuilder stringBuilder=new StringBuilder();
        Iterator<Patent> i=all.iterator();
        while (i.hasNext()){
            Patent patent = i.next();
            if(patent.getTitle()!=null){
                stringBuilder.append("data:"+patent.getTitle());
                stringBuilder.append("\n");
            }
        }
        String path=jarF.getParentFile().toString()+File.separator+"upload"+File.separator+name+".txt";
        FileUtils.writeStringToFile(new File(path),stringBuilder.toString());
        //设置文件路径
        File file = new File(path);
        //File file = new File(realPath , fileName);
        if (file.exists()) {
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.setCharacterEncoding("utf-8");
            try {
                name= URLEncoder.encode(name, "UTF-8").replaceAll("\\+", "%20");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
//                response.setContentType("application/octet-stream");

            // 将文件写入输入流
            FileInputStream fileInputStream = null;
            try {
                fileInputStream = new FileInputStream(file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[0];
            try {
                buffer = new byte[fis.available()];
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fis.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

// 清空response
            response.reset();
            try {
//                    fis = new FileInputStream(file);
//                    bis = new BufferedInputStream(fis);
                OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                response.addHeader("Content-Length", "" + file.length());
                // 设置文件头：最后一个参数是设置下载文件名
                response.setHeader("Content-disposition", "attachment;filename="+name+".txt");
                outputStream.write(buffer);
                outputStream.flush();
                return "下载成功";
            } catch (Exception e) {
                e.printStackTrace();
            } finally { // 做关闭操作

                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        return "下载失败";

    }

    @RequestMapping("/genAbstract")
    @ResponseBody
    public String genAbstract(HttpServletResponse response) throws IOException {
        ApplicationHome h = new ApplicationHome(getClass());
        File jarF = h.getSource();
        String name="03摘要";
        Iterable<Patent> all = patentRepository.findAll();
        StringBuilder stringBuilder=new StringBuilder();
        Iterator<Patent> i=all.iterator();
        while (i.hasNext()){
            Patent patent = i.next();
            if(patent.getEnAbstract()!=null){
                stringBuilder.append("data:"+patent.getEnAbstract());
                stringBuilder.append("\n");
            }
        }
        String path=jarF.getParentFile().toString()+File.separator+"upload"+File.separator+name+".txt";
        FileUtils.writeStringToFile(new File(path),stringBuilder.toString());
        //设置文件路径
        File file = new File(path);
        //File file = new File(realPath , fileName);
        if (file.exists()) {
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.setCharacterEncoding("utf-8");
            try {
                name= URLEncoder.encode(name, "UTF-8").replaceAll("\\+", "%20");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
//                response.setContentType("application/octet-stream");

            // 将文件写入输入流
            FileInputStream fileInputStream = null;
            try {
                fileInputStream = new FileInputStream(file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[0];
            try {
                buffer = new byte[fis.available()];
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fis.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

// 清空response
            response.reset();
            try {
//                    fis = new FileInputStream(file);
//                    bis = new BufferedInputStream(fis);
                OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                response.addHeader("Content-Length", "" + file.length());
                // 设置文件头：最后一个参数是设置下载文件名
                response.setHeader("Content-disposition", "attachment;filename="+name+".txt");
                outputStream.write(buffer);
                outputStream.flush();
                return "下载成功";
            } catch (Exception e) {
                e.printStackTrace();
            } finally { // 做关闭操作

                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        return "下载失败";

    }

    @RequestMapping("/genClassify")
    @ResponseBody
    public String genClassify(HttpServletResponse response) throws IOException {
        ApplicationHome h = new ApplicationHome(getClass());
        File jarF = h.getSource();
        String name="04分类号";
        Iterable<Patent> all = patentRepository.findAll();
        StringBuilder stringBuilder=new StringBuilder();
        Iterator<Patent> i=all.iterator();
        while (i.hasNext()){
            Patent patent = i.next();
            if(patent.getIpcrs()!=null){
                List<String> ipcrs=patent.getIpcrs();
                stringBuilder.append("data:");
                for(int j=0;j<ipcrs.size();j++){
                    stringBuilder.append(ipcrs.get(j)+",");
                }
                stringBuilder.append("\n");
            }
        }
        String path=jarF.getParentFile().toString()+File.separator+"upload"+File.separator+name+".txt";
        FileUtils.writeStringToFile(new File(path),stringBuilder.toString());
        //设置文件路径
        File file = new File(path);
        //File file = new File(realPath , fileName);
        if (file.exists()) {
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.setCharacterEncoding("utf-8");
            try {
                name= URLEncoder.encode(name, "UTF-8").replaceAll("\\+", "%20");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
//                response.setContentType("application/octet-stream");

            // 将文件写入输入流
            FileInputStream fileInputStream = null;
            try {
                fileInputStream = new FileInputStream(file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[0];
            try {
                buffer = new byte[fis.available()];
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fis.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

// 清空response
            response.reset();
            try {
//                    fis = new FileInputStream(file);
//                    bis = new BufferedInputStream(fis);
                OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                response.addHeader("Content-Length", "" + file.length());
                // 设置文件头：最后一个参数是设置下载文件名
                response.setHeader("Content-disposition", "attachment;filename="+name+".txt");
                outputStream.write(buffer);
                outputStream.flush();
                return "下载成功";
            } catch (Exception e) {
                e.printStackTrace();
            } finally { // 做关闭操作

                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        return "下载失败";

    }

    @RequestMapping("/genDescription")
    @ResponseBody
    public String genDescription(HttpServletResponse response) throws IOException {
        ApplicationHome h = new ApplicationHome(getClass());
        File jarF = h.getSource();
        String name="05方案描述";
        Iterable<Patent> all = patentRepository.findAll();
        StringBuilder stringBuilder=new StringBuilder();
        Iterator<Patent> i=all.iterator();
        while (i.hasNext()){
            Patent patent = i.next();
            if(patent.getDescription()!=null){
                stringBuilder.append("data:");
                List<String> description=patent.getDescription();
                for(int j=0;j<description.size();j++){
                    stringBuilder.append(description.get(j)+",");
                }
                stringBuilder.append("\n");
            }
        }
        String path=jarF.getParentFile().toString()+File.separator+"upload"+File.separator+name+".txt";
        FileUtils.writeStringToFile(new File(path),stringBuilder.toString());
        //设置文件路径
        File file = new File(path);
        //File file = new File(realPath , fileName);
        if (file.exists()) {
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.setCharacterEncoding("utf-8");
            try {
                name= URLEncoder.encode(name, "UTF-8").replaceAll("\\+", "%20");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
//                response.setContentType("application/octet-stream");

            // 将文件写入输入流
            FileInputStream fileInputStream = null;
            try {
                fileInputStream = new FileInputStream(file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[0];
            try {
                buffer = new byte[fis.available()];
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fis.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

// 清空response
            response.reset();
            try {
//                    fis = new FileInputStream(file);
//                    bis = new BufferedInputStream(fis);
                OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                response.addHeader("Content-Length", "" + file.length());
                // 设置文件头：最后一个参数是设置下载文件名
                response.setHeader("Content-disposition", "attachment;filename="+name+".txt");
                outputStream.write(buffer);
                outputStream.flush();
                return "下载成功";
            } catch (Exception e) {
                e.printStackTrace();
            } finally { // 做关闭操作

                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        return "下载失败";

    }

    @RequestMapping("/genClaim")
    @ResponseBody
    public String genClaim(HttpServletResponse response) throws IOException {
        ApplicationHome h = new ApplicationHome(getClass());
        File jarF = h.getSource();
        String name="06权力要求";
        Iterable<Patent> all = patentRepository.findAll();
        StringBuilder stringBuilder=new StringBuilder();
        Iterator<Patent> i=all.iterator();
        while (i.hasNext()){
            Patent patent = i.next();
            if(patent.getDescription()!=null){
                List<String> claim=patent.getClaim();
                stringBuilder.append("data:");
                for(int j=0;j<claim.size();j++){
                    stringBuilder.append(claim.get(j)+",");
                }
                stringBuilder.append("\n");
            }
        }
        String path=jarF.getParentFile().toString()+File.separator+"upload"+File.separator+name+".txt";
        FileUtils.writeStringToFile(new File(path),stringBuilder.toString());
        //设置文件路径
        File file = new File(path);
        //File file = new File(realPath , fileName);
        if (file.exists()) {
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.setCharacterEncoding("utf-8");
            try {
                name= URLEncoder.encode(name, "UTF-8").replaceAll("\\+", "%20");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
//                response.setContentType("application/octet-stream");

            // 将文件写入输入流
            FileInputStream fileInputStream = null;
            try {
                fileInputStream = new FileInputStream(file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[0];
            try {
                buffer = new byte[fis.available()];
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fis.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

// 清空response
            response.reset();
            try {
//                    fis = new FileInputStream(file);
//                    bis = new BufferedInputStream(fis);
                OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                response.addHeader("Content-Length", "" + file.length());
                // 设置文件头：最后一个参数是设置下载文件名
                response.setHeader("Content-disposition", "attachment;filename="+name+".txt");
                outputStream.write(buffer);
                outputStream.flush();
                return "下载成功";
            } catch (Exception e) {
                e.printStackTrace();
            } finally { // 做关闭操作

                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        return "下载失败";

    }

    @RequestMapping("/genApplicants")
    @ResponseBody
    public String genApplicants(HttpServletResponse response) throws IOException {
        ApplicationHome h = new ApplicationHome(getClass());
        File jarF = h.getSource();
        String name="07申请人";
        Iterable<Patent> all = patentRepository.findAll();
        StringBuilder stringBuilder=new StringBuilder();
        Iterator<Patent> i=all.iterator();
        while (i.hasNext()){
            Patent patent = i.next();

            if(patent.getDescription()!=null){
                stringBuilder.append("data:");
                List<String> applicants=patent.getApplicants();
                for(int j=0;j<applicants.size();j++){
                    Map<String, String> map = JSON.parseObject(applicants.get(j), new TypeReference<Map<String, String>>(){});
                    if(map.get("name")!=null){
                        stringBuilder.append(map.get("name")+",");
                    }else {
                        stringBuilder.append(map.get("lastName")+",");
                    }

                }
                stringBuilder.append("\n");
            }
        }
        String path=jarF.getParentFile().toString()+File.separator+"upload"+File.separator+name+".txt";
        FileUtils.writeStringToFile(new File(path),stringBuilder.toString());
        //设置文件路径
        File file = new File(path);
        //File file = new File(realPath , fileName);
        if (file.exists()) {
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.setCharacterEncoding("utf-8");
            try {
                name= URLEncoder.encode(name, "UTF-8").replaceAll("\\+", "%20");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
//                response.setContentType("application/octet-stream");

            // 将文件写入输入流
            FileInputStream fileInputStream = null;
            try {
                fileInputStream = new FileInputStream(file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[0];
            try {
                buffer = new byte[fis.available()];
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fis.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

// 清空response
            response.reset();
            try {
//                    fis = new FileInputStream(file);
//                    bis = new BufferedInputStream(fis);
                OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                response.addHeader("Content-Length", "" + file.length());
                // 设置文件头：最后一个参数是设置下载文件名
                response.setHeader("Content-disposition", "attachment;filename="+name+".txt");
                outputStream.write(buffer);
                outputStream.flush();
                return "下载成功";
            } catch (Exception e) {
                e.printStackTrace();
            } finally { // 做关闭操作

                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        return "下载失败";

    }

    @RequestMapping("/genInventors")
    @ResponseBody
    public String genInventors(HttpServletResponse response) throws IOException {
        ApplicationHome h = new ApplicationHome(getClass());
        File jarF = h.getSource();
        String name="08发明人";
        Iterable<Patent> all = patentRepository.findAll();
        StringBuilder stringBuilder=new StringBuilder();
        Iterator<Patent> i=all.iterator();
        while (i.hasNext()){
            Patent patent = i.next();
            if(patent.getInventors()!=null){
                stringBuilder.append("data:");
                List<String> inventors=patent.getInventors();
                for(int j=0;j<inventors.size();j++){
                    Map<String, String> map = JSON.parseObject(inventors.get(j), new TypeReference<Map<String, String>>(){});
                    if(map.get("name")!=null){
                        stringBuilder.append(map.get("name")+",");
                    }else {
                        stringBuilder.append(map.get("lastName")+",");
                    }

                }
                stringBuilder.append("\n");
            }
        }
        String path=jarF.getParentFile().toString()+File.separator+"upload"+File.separator+name+".txt";
        FileUtils.writeStringToFile(new File(path),stringBuilder.toString());
        //设置文件路径
        File file = new File(path);
        //File file = new File(realPath , fileName);
        if (file.exists()) {
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.setCharacterEncoding("utf-8");
            try {
                name= URLEncoder.encode(name, "UTF-8").replaceAll("\\+", "%20");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
//                response.setContentType("application/octet-stream");

            // 将文件写入输入流
            FileInputStream fileInputStream = null;
            try {
                fileInputStream = new FileInputStream(file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[0];
            try {
                buffer = new byte[fis.available()];
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fis.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

// 清空response
            response.reset();
            try {
//                    fis = new FileInputStream(file);
//                    bis = new BufferedInputStream(fis);
                OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                response.addHeader("Content-Length", "" + file.length());
                // 设置文件头：最后一个参数是设置下载文件名
                response.setHeader("Content-disposition", "attachment;filename="+name+".txt");
                outputStream.write(buffer);
                outputStream.flush();
                return "下载成功";
            } catch (Exception e) {
                e.printStackTrace();
            } finally { // 做关闭操作

                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        return "下载失败";

    }

    @RequestMapping("/genLog")
    @ResponseBody
    public String genLog(HttpServletResponse response) throws IOException {
        ApplicationHome h = new ApplicationHome(getClass());
        File jarF = h.getSource();
        String name="log";
        Iterable<Patent> all = patentRepository.findAll();
        StringBuilder stringBuilder=new StringBuilder();
        Iterator<Patent> i=all.iterator();
        while (i.hasNext()){
            Patent patent = i.next();
            if(patent.getInventors()!=null){

                Map<String, String> map = JSON.parseObject(patent.getPublicNum(), new TypeReference<Map<String, String>>(){});
                stringBuilder.append("pubic:"+map.get("country").toString()+map.get("docNumber").toString());
                stringBuilder.append("\n");
                stringBuilder.append("data:公开号[1]+申请号[1]+标题[1]+摘要[1]+分类号[1]+");
                // +方案描述[1]+权力要求[1]+申请人[1]+发明人[1]
                if(patent.getDescription()!=null&&patent.getDescription().size()>0){
                    stringBuilder.append("方案描述[1]+");
                }else {
                    stringBuilder.append("方案描述[0]+");
                }
                if(patent.getClaim()!=null&&patent.getClaim().size()>0){
                    stringBuilder.append("权力要求[1]+");
                }else {
                    stringBuilder.append("权力要求[0]+");
                }
                if(patent.getApplicants()!=null&&patent.getApplicants().size()>0){
                    stringBuilder.append("申请人[1]+");
                }else {
                    stringBuilder.append("申请人[0]+");
                }
                if(patent.getInventors()!=null&&patent.getInventors().size()>0){
                    stringBuilder.append("发明人[1]\n");
                }else {
                    stringBuilder.append("发明人[0]\n");
                }
            }
        }
        String path=jarF.getParentFile().toString()+File.separator+"upload"+File.separator+name+".txt";
        FileUtils.writeStringToFile(new File(path),stringBuilder.toString());
        //设置文件路径
        File file = new File(path);
        //File file = new File(realPath , fileName);
        if (file.exists()) {
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.setCharacterEncoding("utf-8");
            try {
                name= URLEncoder.encode(name, "UTF-8").replaceAll("\\+", "%20");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
//                response.setContentType("application/octet-stream");

            // 将文件写入输入流
            FileInputStream fileInputStream = null;
            try {
                fileInputStream = new FileInputStream(file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[0];
            try {
                buffer = new byte[fis.available()];
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fis.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

// 清空response
            response.reset();
            try {
//                    fis = new FileInputStream(file);
//                    bis = new BufferedInputStream(fis);
                OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                response.addHeader("Content-Length", "" + file.length());
                // 设置文件头：最后一个参数是设置下载文件名
                response.setHeader("Content-disposition", "attachment;filename="+name+".txt");
                outputStream.write(buffer);
                outputStream.flush();
                return "下载成功";
            } catch (Exception e) {
                e.printStackTrace();
            } finally { // 做关闭操作

                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        return "下载失败";

    }
}
